<template>
  <el-dialog
    :visible.sync="visible"
    :title="dataForm.details ? '详情' : !dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="close()"
    @open="open()"
    :destroy-on-close="true"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmitHandle()"
      :label-width="$i18n.locale === 'en-US' ? '120px' : '120px'"
      label-position="right"
      :disabled="disabled"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="公司名称" prop="corporateName">
            <el-input
              type="text"
              v-model="dataForm.corporateName"
              :placeholder="disabled ? '' : '公司名称'"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="营业时间" prop="businessHours">
            <el-input
              type="text"
              v-model="dataForm.businessHours"
              :placeholder="disabled ? '' : '营业时间,如:07:00-21:00'"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <p class="pdl60">
           <span style="color:red;">*</span>公司图片<span>(支持png、jpg，建议尺寸750*420px，最多5张)</span>
          </p>
        </el-col>
        <el-col :span="24">
          <el-form-item class="imgLabel" label="" prop="corporatePhoto">
            <div
              v-if="dataForm.details"
              style="display: flex; align-items: center"
            >
              <img
                :src="img.url"
                alt=""
                v-for="(img, i) in cpFileList"
                :key="i"
                style="width: 140px; height: 140px; margin-right: 10px"
              />
            </div>
            <div v-else>
              <el-upload
                class="avatar-uploader"
                :action="url"
                list-type="picture-card"
                :on-remove="handleRemoveCP"
                :on-success="handleAvatarSuccessCP"
                :before-upload="
                  (file) => beforeUploadHandle(file, 'cpFileList')
                "
                :file-list="cpFileList"
                :limit="5"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item
            class="imgLabel"
            label="营业执照"
            prop="businessLicense"
          >
            <div
              v-if="dataForm.details"
              style="display: flex; align-items: center"
            >
              <img
                :src="img.url"
                alt=""
                v-for="(img, i) in blFileList"
                :key="i"
                style="width: 140px; height: 140px; margin-right: 10px"
              />
            </div>
            <div v-else>
              <el-upload
                class="avatar-uploader"
                :action="url"
                list-type="picture-card"
                :on-remove="handleRemoveBL"
                :on-success="handleAvatarSuccessBL"
                :before-upload="
                  (file) => beforeUploadHandle(file, 'blFileList')
                "
                :file-list="blFileList"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="公司地址" prop="position">
            <el-input
              type="text"
              v-model="dataForm.position"
              :placeholder="disabled ? '' : '公司地址'"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="经度" prop="longitude">
            <el-input
              type="number"
              v-model="dataForm.longitude"
              :placeholder="disabled ? '' : '经度'"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度" prop="latitude">
            <el-input
              type="number"
              v-model="dataForm.latitude"
              :placeholder="disabled ? '' : '纬度'"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="联系人" prop="rentalName">
            <el-input
              type="text"
              v-model="dataForm.rentalName"
              :placeholder="disabled ? '' : '联系人'"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="rentalPhone">
            <el-input
              type="number"
              v-model="dataForm.rentalPhone"
              :placeholder="disabled ? '' : '联系电话'"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!-- <el-col :span="12">
          <el-form-item label="监督电话" prop="supervisePhone">
            <el-input
              type="number"
              v-model="dataForm.supervisePhone"
              :placeholder="disabled ? '' : '监督电话'"
            ></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="包车路线" prop="routeIdList">
            <SelectComponent
              v-model="dataForm.routeIdList"
              :options="bcOptions"
              :placeholder="disabled ? '' : '包车路线'"
              :multiple="true"
              ref="route_sc"
            >
            </SelectComponent>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template slot="footer" v-if="!disabled">
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
      <!-- 裁剪框 -->
    <cropper-dlg
      v-if="showCropper"
      :dialogVisible.sync="showCropper"
      :img-file="currentFile"
      ref="vueCropper"
      @upload="cropperUpload"
    ></cropper-dlg>
  </el-dialog>
</template>
  
  <script>
import Cookies from "js-cookie";
import debounce from "lodash/debounce";
import mixinRegionModule from "@/mixins/region-module";

export default {
  mixins: [mixinRegionModule],

  data() {
    return {
      currentFile: "",
      cropperIndex: null,
      showCropper: false, //裁剪弹框
      isCropper: true, //上传之前是否显示裁剪
      visible: false,
      url: `${
        window.SITE_CONFIG["apiURL"]
      }/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
      cpFileList: [],
      blFileList: [],
      bcOptions: [],
      dataForm: {
        id: "",
        corporateName: "",
        businessHours: "",
        corporatePhoto: "",
        businessLicense: "",
        position: "",
        longitude: "",
        latitude: "",
        rentalName: "",
        rentalPhone: "",
        supervisePhone: "",
        routeIdList: "",
      },
    };
  },
  props: { disabled: Boolean },
  computed: {
    dataRule() {
      return {
        corporateName: [
          { required: true, message: "请输入公司名称", trigger: "blur" },
        ],
        businessHours: [
          { required: true, message: "请输入营业时间", trigger: "blur" },
        ],
        position: [
          { required: true, message: "请输入公司地址", trigger: "blur" },
        ],
        longitude: [
          { required: true, message: "请输入经度", trigger: "blur" },
        ],
        latitude: [
          { required: true, message: "请输入纬度", trigger: "blur" },
        ],
        rentalName: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        rentalPhone: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
        ],
        supervisePhone: [
          { required: true, message: "请输入监督电话", trigger: "blur" },
        ]
      };
    },
  },
  methods: {
    open() {
      this.$http
        .get("/travel/travel/rentalcarroute/page", {
          params: {
            page: 1,
            limit: 9999,
          },
        })
        .then(({ data: res }) => {
          res.data.list.forEach((l) => {
            this.bcOptions.push({ dictValue: l.id, dictLabel: l.routeName });
          });
        });
    },
    handleRemoveCP(file, fileList) {
      this.cpFileList = fileList.map((item) => {
        return item;
      });
    },
    // handleRemoveCP(file) {
    //   let fidx = this.cpFileList.findIndex((f) => f.uid == file.uid);
    //   this.cpFileList.splice(fidx, 1);
    // },
    handleAvatarSuccessCP(res, file) {
      //this.cpFileList.push(file);
      this.cpFileList.push({
        name: "",
        url: res.data.url,
      });
    },
    // handleRemoveBL(file) {
    //   let fidx = this.blFileList.findIndex((f) => f.uid == file.uid);
    //   this.blFileList.splice(fidx, 1);
    // },
    handleRemoveBL(file, fileList) {
      this.blFileList = fileList.map((item) => {
        return item;
      });
    },
    handleAvatarSuccessBL(res, file) {
      //this.blFileList.push(file);
      this.blFileList.push({
        name: "",
        url: res.data.url,
      });
    },
    // 上传之前
    beforeUploadHandle(file, name) {
      if (
        file.type !== "image/jpg" &&
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/gif"
      ) {
        this.$message.error(
          this.$t("upload.tip", {
            format: "jpg、png、gif",
          })
        );
        return false;
      }
      if (this.isCropper) {
        //显示裁剪
        this.currentFile = file;
        this.cropperIndex = name;
        this.showCropper = true;
        this.$nextTick(() => {
          this.$refs.vueCropper.init();
        });
        return false;
      }
    },

    cropperUpload(data) {
      this.showCropper = false;
      if (data != "close") {
        //裁剪成功后获取的图片
        this.$http.post("/oss/file/aliyunUpload", data).then((res) => {
          if (res.data.code == 0) {
            if (this.cropperIndex == "blFileList") {
              //营业执照
              this.handleAvatarSuccessBL(res.data);
            } else {
              //公司照片
              this.handleAvatarSuccessCP(res.data);
            }
          }
        });
      }
    },
    close() {
      this.cpFileList = [];
      this.blFileList = [];
      this.bcOptions = [];
      this.dataForm = {
        id: "",
        corporateName: "",
        businessHours: "",
        corporatePhoto: "",
        businessLicense: "",
        position: "",
        longitude: "",
        latitude: "",
        rentalName: "",
        rentalPhone: "",
        supervisePhone: "",
        routeIdList: "",
      };
      this.$emit("changeDisabled");
    },

    init() {
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.getInfo();
        }
      });
    },
    // 获取信息
    getInfo() {
      this.$http
        .get("/travel/travel/rentalcarcompany/" + this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
          };
          if (res.data.corporatePhoto) {
            let temp = res.data.corporatePhoto.split(",") || [];
            temp.forEach((p) => {
              this.cpFileList.push({ url: p });
            });
          }
          if (res.data.businessLicense) {
            let temp = res.data.businessLicense.split(",") || [];
            temp.forEach((p) => {
              this.blFileList.push({ url: p });
            });
          }
          this.$refs.route_sc.selectValue =
            this.dataForm.routeIdList.split(",");
        })
        .catch(() => {});
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }

          this.dataForm.corporatePhoto = "";
          let cptemp = [];
          if (this.cpFileList.length == 0)
            return this.$message.error("请上传公司图片");
          this.cpFileList.forEach((f, i) => {
            let url = f.url;
            if (f.response && f.response.data && f.response.data.url)
              url = f.response.data.url;
            cptemp.push(url);
          });
          this.dataForm.corporatePhoto = cptemp.join(",");

          this.dataForm.businessLicense = "";
          let bltemp = [];
          if (this.blFileList.length == 0)
            return this.$message.error("请上传营业执照");
          this.blFileList.forEach((f, i) => {
            let url = f.url;
            if (f.response && f.response.data && f.response.data.url)
              url = f.response.data.url;
            bltemp.push(url);
          });
          this.dataForm.businessLicense = bltemp.join(",");
          this.dataForm.longitude = parseFloat(this.dataForm.longitude) || "";
          this.dataForm.latitude = parseFloat(this.dataForm.latitude) || "";
          this.dataForm.rentalPhone =
            parseFloat(this.dataForm.rentalPhone) || "";
          this.dataForm.supervisePhone =
            parseFloat(this.dataForm.supervisePhone) || "";
          if (typeof this.dataForm.routeIdList == "object") {
            this.dataForm.routeIdList =
              this.dataForm.routeIdList.length > 0
                ? this.dataForm.routeIdList.join(",")
                : "";
          }
          this.$http[!this.dataForm.id ? "post" : "put"](
            !this.dataForm.id
              ? "/travel/travel/rentalcarcompany"
              : "/travel/travel/rentalcarcompany",
            this.dataForm
          )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
};
</script>
  <style scoped lang="scss">
::v-deep .imgLabel {
  & > label::before {
    content: "*";
    color: #f56c6c;
    margin-right: 4px;
  }
}
</style>